import './ReceiveOrg.scss'

import { useState, useMemo } from 'react'
import { Tree, Input, Button } from 'antd'
import { useEventEmitter, useMount, useRequest } from 'ahooks'
import { PlusOutlined, ApiOutlined, DisconnectOutlined } from '@ant-design/icons'

import { Http } from '../../../Api'
import { ModalBox } from '../../../Modal/ModalBox'

const getParentKey = (key, tree, value) => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
            if (node.children.some(item => item[value] === key)) parentKey = node[value]
            else if (getParentKey(key, node.children, value)) parentKey = getParentKey(key, node.children, value)
        }
    }
    return parentKey
}

const LoopTree = (data, search, type) => {
    return data.map(item => {
        const strTitle = type === 0 ? item.tableName : item.organizationName
        const index = strTitle.indexOf(search)
        const beforeStr = strTitle.substring(0, index)
        const afterStr = strTitle.slice(index + search.length)
        const title =
            index > -1 ? (
                <span key={item.uuid}>
                    {beforeStr}
                    <span className="site-tree-search-value">{search}</span>
                    {afterStr}
                </span>
            ) : (
                <span key={item.uuid}>{strTitle}</span>
            )
        return {
            ...item,
            [type === 0 ? 'tableName' : 'organizationName']: title,
            ...(item.children ? { children: LoopTree(item.children, search, type) } : {}),
        }
    })
}

const getKeys = (data, name, value, uuid, tree, key) => {
    return data
        .map(item => {
            if (item[name].indexOf(value) > -1) {
                return getParentKey(item[uuid], tree, key)
            }
            return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
}

export const ReceiveOrg = () => {
    const [selectedKeys, setSelectedKeys] = useState([])
    const [OptionsCall, setOptionsCall] = useState()

    const [TreeDataA01, setTreeDataA01] = useState([])
    const [TreeDataA02, setTreeDataA02] = useState([])

    const [DataA01, setDataA01] = useState([])
    const [DataA02, setDataA02] = useState([])

    const [searchValueA01, setSearchValueA01] = useState('')
    const [searchValueA02, setSearchValueA02] = useState('')

    const [expandedKeysA01, setExpandedKeysA01] = useState([])
    const [expandedKeysA02, setExpandedKeysA02] = useState([])

    const [autoExpandParentA01, setAutoExpandParentA01] = useState(true)
    const [autoExpandParentA02, setAutoExpandParentA02] = useState(true)

    const onSelect = e => {
        if (e.length !== 0) setSelectedKeys(e)
    }

    const { runAsync: getTreeA01 } = useRequest(Http, { manual: true, onSuccess: res => setTreeDataA01(res) })
    const { runAsync: getTreeA02 } = useRequest(Http, { manual: true, onSuccess: res => setTreeDataA02(res) })
    const { runAsync: getDefaultDataA01 } = useRequest(Http, { manual: true, onSuccess: res => setDataA01(res.list) })
    const { runAsync: getDefaultDataA02 } = useRequest(Http, { manual: true, onSuccess: res => setDataA02(res.list) })

    const treeDataA01 = useMemo(() => LoopTree(TreeDataA01, searchValueA01, 0), [TreeDataA01, searchValueA01])
    const treeDataA02 = useMemo(() => LoopTree(TreeDataA02, searchValueA02, 1), [TreeDataA02, searchValueA02])

    const onExpandA01 = key => {
        setExpandedKeysA01(key)
        setAutoExpandParentA01(false)
    }

    const onExpandA02 = key => {
        setExpandedKeysA02(key)
        setAutoExpandParentA02(false)
    }

    const onChangeA01 = e => {
        const { value } = e.target
        const keys = getKeys(DataA01, 'name', value, 'mdmCode', TreeDataA01, 'uuid')
        setSearchValueA01(value)
        setExpandedKeysA01(keys)
        setAutoExpandParentA01(true)
    }

    const onChangeA02 = e => {
        const { value } = e.target
        const keys = getKeys(DataA02, 'tableName', value, 'uuid', TreeDataA02, 'organizationUuid')
        console.log(keys)
        setSearchValueA02(value)
        setExpandedKeysA02(keys)
        setAutoExpandParentA02(true)
    }

    useMount(() => {
        getTreeA01({ url: 'getMasterDataOrgTree' })
        getTreeA02({ url: 'getOrganizationTree' })
        getDefaultDataA01({ url: 'getMasterDataOrgList' })
        getDefaultDataA02({ url: 'getOrganization', data: { pageIndex: 10000 } })
    })

    // 解除绑定
    const onRelieve = data => {
        const { uuid, organizationUuid } = data
        setOptionsCall({
            type: 'OrgBindMapping',
            data: {
                title: '解除绑定',
                A01: DataA01.find(v => v.mdmCode === uuid),
                A02: DataA02.find(v => v.uuid === organizationUuid),
                type: 0,
            },
        })
    }
    // 绑定数据
    const onBinding = data => {
        const [mdmCode] = selectedKeys
        setOptionsCall({
            type: 'OrgBindMapping',
            data: {
                title: '绑定操作',
                A01: DataA01.find(v => v.mdmCode === mdmCode),
                A02: DataA02.find(v => v.uuid === data.organizationUuid),
                type: 1,
            },
        })
    }
    // 添加新数据
    const onAdded = () => {
        const [mdmCode] = selectedKeys
        setOptionsCall({
            type: 'OrgAddMapping',
            data: {
                title: '新增组织机构',
                data: DataA01.find(v => v.mdmCode === mdmCode),
            },
        })
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'refresh') {
            console.log('更新数据')
            getTreeA01({ url: 'getMasterDataOrgTree' })
            getTreeA02({ url: 'getOrganizationTree' })
        }
    })

    return (
        <div className="ReceiveOrg">
            <div className="Left">
                <Input
                    className="Options"
                    size="large"
                    placeholder="请输入组织机构名称"
                    onChange={onChangeA01}
                    allowClear
                />
                <Tree
                    defaultExpandAll
                    fieldNames={{ title: 'tableName', key: 'uuid' }}
                    selectedKeys={selectedKeys}
                    onSelect={onSelect}
                    onExpand={onExpandA01}
                    expandedKeys={expandedKeysA01}
                    autoExpandParent={autoExpandParentA01}
                    treeData={treeDataA01}
                    titleRender={e => {
                        return (
                            <div key={e.uuid} className="orgList">
                                <div className="Title">
                                    <div>{e.tableName}</div>
                                    <div className="OrgBind">{e.organizationName}</div>
                                </div>
                                <div className="options">
                                    {e.organizationUuid ? (
                                        <Button type="link" icon={<DisconnectOutlined />} onClick={() => onRelieve(e)}>
                                            解绑
                                        </Button>
                                    ) : (
                                        selectedKeys[0] === e.uuid && (
                                            <Button type="link" icon={<PlusOutlined />} onClick={() => onAdded()}>
                                                添加
                                            </Button>
                                        )
                                    )}
                                </div>
                            </div>
                        )
                    }}
                />
            </div>
            <div className="Right">
                <Input
                    className="Options"
                    size="large"
                    placeholder="请输入组织机构名称"
                    onChange={onChangeA02}
                    allowClear
                />
                <Tree
                    defaultExpandAll
                    fieldNames={{ title: 'organizationName', key: 'organizationUuid' }}
                    selectable={false}
                    onExpand={onExpandA02}
                    expandedKeys={expandedKeysA02}
                    autoExpandParent={autoExpandParentA02}
                    treeData={treeDataA02}
                    titleRender={e => {
                        return (
                            <div key={e.organizationUuid} className="orgList">
                                <div className="Title">
                                    <div>{e.organizationName}</div>
                                    <div className="OrgBind">{e.tableName}</div>
                                </div>
                                <div className="options">
                                    {e.uuid ? (
                                        <Button type="link" icon={<DisconnectOutlined />} onClick={() => onRelieve(e)}>
                                            解绑
                                        </Button>
                                    ) : (
                                        selectedKeys.length !== 0 && (
                                            <Button type="link" icon={<ApiOutlined />} onClick={() => onBinding(e)}>
                                                绑定
                                            </Button>
                                        )
                                    )}
                                </div>
                            </div>
                        )
                    }}
                />
            </div>

            <ModalBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}
